package com.zys.hotel_management.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Date;

public class JwtUtils {

    // 生成密钥对（实际项目建议从配置或文件加载）
    private static final KeyPair KEY_PAIR = generateKeyPair();
    private static final long EXPIRATION_TIME = 86400000;

    private static KeyPair generateKeyPair() {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            return keyPairGenerator.generateKeyPair();
        } catch (Exception e) {
            throw new RuntimeException("生成密钥对失败", e);
        }
    }

    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.RS256, KEY_PAIR.getPrivate())
                .compact();
    }

    public static String validateToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(KEY_PAIR.getPublic())
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }
}